package com.mitcub.panda.controller;

import com.mitcub.panda.entity.Admin;
import com.mitcub.panda.mapper.AdminMapper;
import com.mitcub.panda.utils.RespResult;
import com.wf.captcha.utils.CaptchaUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @项目名称: panda
 * @类名称: LoginController
 * @类描述:
 * @作者: tangloong
 * @创建时间: 2021/7/21 13:59
 */

@Controller
@Slf4j
public class LoginController {

    @Resource
    AdminMapper adminMapper;

    @GetMapping(value={"/","/login"})
    public String login(){
        return "login";
    }

    /**
     * 获取验证码
     * @param response
     * @return
     */
    @GetMapping("/login/captcha")
    public void captcha(HttpServletRequest request, HttpServletResponse response) throws Exception {
        CaptchaUtil.out(request, response);
    }

    @ResponseBody
    @PostMapping(value = "/login")
    public RespResult login(HttpServletRequest request,String username, String password,String captcha, String rememberMe) {
        Admin admin = adminMapper.selectByUsername(username);

        if (null == admin){
            return RespResult.error("用户不存在");
        }
        if(!DigestUtils.md5Hex(password).equals(admin.getPassword())){
            return RespResult.error("密码错误");
        }
        request.getSession().setAttribute("USER",admin);
        return RespResult.success("登录成功","/index");
    }

    @RequestMapping("/login/logout")
    public String LogoutController(HttpServletRequest request){
        request.getSession().setAttribute("USER", null);
        request.getSession().setAttribute("uid", 0);
        return "redirect:/";
    }

}


















